package com.song.service;

import com.github.pagehelper.PageInfo;
import com.song.mapper.AdminroleMapper;
import com.song.mapper.AdminsMapper;
import com.song.pojo.Admins;
import com.song.pojo.AdminsExample;
import com.song.pojo.AdminsQueryVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 管理员的服务层
 *
 * @author song
 */
@Service
public class AdminsService {
    @Resource
    private AdminsMapper adminsMapper;
    @Resource
    private AdminroleMapper adminroleMapper;

    /**
     * 管理员登录
     * @param loginName
     * @param adminPwd
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public List<Admins> login(String loginName, String adminPwd){
        AdminsExample example = new AdminsExample();
        AdminsExample.Criteria criteria = example.createCriteria();
        boolean name = (loginName != null && !"".equals(loginName.trim()));
        boolean password = (adminPwd != null&&!"".equals(adminPwd.trim()));
        if(name&&password){
            criteria.andLoginNameEqualTo(loginName);
            criteria.andAdminPwdEqualTo(adminPwd);
            List<Admins> admins = adminsMapper.selectByExample(example);
            //登录查询成功，更新登录时间
            for (Admins admin : admins) {
                admin.setLastLoginTime(new Date());
                adminsMapper.updateByPrimaryKeySelective(admin);
            }
            return admins;
        }
        return null;
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @param vo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public PageInfo<Admins> queryAdmins(Integer pageNum, Integer pageSize, AdminsQueryVO vo) {
        AdminsExample example = new AdminsExample();
        AdminsExample.Criteria criteria = example.createCriteria();
        if (vo.getLoginName() != null&&"".equals(vo.getLoginName().trim())){
            criteria.andLoginNameEqualTo(vo.getLoginName().trim());
        }
        if (vo.getLoginName() != null&&"".equals(vo.getLoginName().trim())){
            criteria.andLoginNameEqualTo(vo.getLoginName().trim());
        }
        if (vo.getLoginName() != null&&"".equals(vo.getLoginName().trim())){
            criteria.andLoginNameEqualTo(vo.getLoginName().trim());
        }
        return null;

    }
}
